package app.controllers.admin.game;

import app.Const;
import app.models.DaoKit;
import app.models.game.GameAwards;
import app.models.game.GameGift;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.jfinal.plugin.activerecord.Page;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 奖项设置
 * </p>
 *
 * @author Jerry Ou
 * @version 1.0 2014-02-12 13:41
 * @since JDK 1.6
 */
public class AwardsController extends BasicController {

    public void index() {
        render("index.ftl");
    }

    public void list() {
        final DatatablesCriterias criterias = getCriterias();
        Page<GameAwards> page = GameAwards.dao.datatable(criterias);

        renderDataTables(page, criterias);
    }

    public void status() {
        try {
            long id = getParaToLong("DATA", 0l);
            boolean status = getParaToBoolean("state", false);
            if (id != 0) {
                GameAwards gameAwards = new GameAwards();
                gameAwards.set("id", id);
                gameAwards.set("state", !status);
                gameAwards.update();
            }
            renderJson(AjaxMessage.ok("操作成功"));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(AjaxMessage.error("操作失败"));
        }
    }

    public void create() {
        GameAwards awards = new GameAwards();

        List<GameGift> gifts = GameGift.dao.list();

        setAttr("oper", "create");
        setAttr("gifts", gifts);
        setAttr("awards", awards);
        render("item.ftl");
    }

    public void edit() {
        GameAwards awards = GameAwards.dao.findById(getPara());

        List<GameGift> gifts = GameGift.dao.list();

        setAttr("oper", "edit");
        setAttr("gifts", gifts);
        setAttr("awards", awards);
        render("item.ftl");
    }

    public void save() {
        GameAwards awards = getModel(GameAwards.class, "awards");
        if (DaoKit.isNew(awards)) {
            awards.set("create_time", new Date());
            awards.save();
        } else {
            awards.update();
        }
        redirect("/admin/game/awards/index");
    }

    public void remove() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);
        if (DaoKit.batch_remove(SqlKit.sql("gameawards.remove"), ids)) {
            renderSuccess();
        } else {
            renderError("删除出现错误");
        }
    }

}
